//
//  GnetQM_XMPPManager.m
//  SingleSignOn
//
//  Created by 王艳 on 16/1/12.
//  Copyright (c) 2016年 wangyan. All rights reserved.
//

#import "DEFINE.h"
#import "GnetQM_XMPPManager.h"



@implementation GnetQM_XMPPManager

#pragma mark 开启单例
static GnetQM_XMPPManager *sharedManager;
+(GnetQM_XMPPManager*)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager=[[GnetQM_XMPPManager alloc]init];
        
        [sharedManager setupStream];
        
    });
    return sharedManager;
}


#pragma mark 注册
-(void)registerMothod:(void(^)(BOOL))b
{
    logoinorSignin = YES;
    sharedManager.signin = b;
    //进行连接，连接失败 在进行注册操作
    [sharedManager connectLogin:^(BOOL isSucceed) {
        //登录必定是失败，然后进行注册步骤
        
        if ([xmppStream supportsInBandRegistration]) {
            
            NSError *error ;
            [xmppStream setMyJID:[XMPPJID jidWithUser:[userDefaults objectForKey:kXMPPmyJID] domain:kXMPP_DOMAIN resource:kXMPP_ZIYUANMING]];
            
            //domain 是找服务器要这个名字就是服务器主机名字，在安装时候的名字
            //resource 这个是一个标示，具体参照QQ来自于土豪金
            if (![xmppStream registerWithPassword:[userDefaults objectForKey:kXMPPmyPassword]error:&error]) {
                
                sharedManager.signin(NO);
            }
        }
    }];
}

- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error
{
    //重复注册了用户名
    [xmppStream disconnect];
    sharedManager.signin(NO);
    logoinorSignin=NO;
    NSLog(@"注册名已存在");
    
}

- (void)xmppStreamDidRegister:(XMPPStream *)sender
{//注册成功
    
    [xmppStream disconnect];
    sharedManager.signin(YES);
    logoinorSignin=NO;
    NSLog(@"注册成功");
}

#pragma mark Connect/disconnect  登录
- (BOOL)connectLogin:(void(^)(BOOL))a
{
    sharedManager.logoin=a;
    if (![xmppStream isDisconnected]) {
        return YES;
    }
    
    NSString *myJID = [userDefaults stringForKey:kXMPPmyJID];
    NSString *myPassword = [userDefaults stringForKey:kXMPPmyPassword];
    
    NSLog(@"MyJID = %@",myJID);
    
    
    if (myJID.length==0 || myPassword.length == 0) {
        //        UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"警告" message:@"检查是否输入了用户名密码" delegate:self cancelButtonTitle:kXMPP_localAction otherButtonTitles: nil];
        //        [alert show];
        //		return NO;
    }
//    NSLog(@"%@",kXMPP_DOMAIN);
    [xmppStream setMyJID:[XMPPJID jidWithUser:myJID domain:kXMPP_DOMAIN resource:kXMPP_ZIYUANMING]];
    password=myPassword;
    NSError *error = nil;
    //进行连接
    if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error]) {
        NSLog(@"连接错误");
		UIAlertController *alVC = [UIAlertController alertControllerWithTitle:kXMPP_connectFail message:nil preferredStyle:UIAlertControllerStyleAlert];
		UIAlertAction *title = [UIAlertAction actionWithTitle:kXMPP_connectFail style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
			
		}];
		UIAlertAction *cancel = [UIAlertAction actionWithTitle:kXMPP_localAction style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
			
		}];
		[alVC addAction:title];
		[alVC addAction:cancel];
		UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
		UIViewController *topVC = appRootVC;
		if (topVC.presentedViewController) {
			topVC = topVC.presentedViewController;
		}
		[topVC presentViewController:alVC animated:YES completion:^{
			
		}];
//        UIAlertView *al=[[UIAlertView alloc]initWithTitle:kXMPP_connectFail message:nil delegate:self cancelButtonTitle:kXMPP_localAction otherButtonTitles: nil];
//        [al show];
        return NO;
    }
    return YES;
}

- (void)disconnect
{
    //发送离线消息
    [self goOffline];
    [xmppStream disconnect];
    //停止重连
    [xmppReconnect setAutoReconnect:NO];
}

- (void)goOffline
{
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    
    [xmppStream sendElement:presence];
    
    
}

#pragma mark XMPPStream Delegate
- (void)xmppStreamWillConnect:(XMPPStream *)sender
{
    //将要开始连接
    NSLog(@"将要开始连接");
}

- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
//    NSLog(@"连接成功%@",password);
	NSLog(@"连接成功");

    NSError *error = nil;
    
    if (![xmppStream authenticateWithPassword:password error:&error])
    {
        NSLog(@"Error authenticating: %@", error);
    }
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    NSLog(@"完成认证，发送在线状态");
    [self goOnline];
    sharedManager.logoin(YES);
    
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    NSLog(@"认证错误");
    if (!logoinorSignin) {
        [xmppStream disconnect];
    }
    
    sharedManager.logoin(NO);
}

- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
    
}

- (void)goOnline{
    XMPPPresence *presence = [XMPPPresence presence];
    // type="available" is implicit
    [xmppStream sendElement:presence];
    NSLog(@"发送完在线状态");
}

#pragma mark - 单点登录
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error{
    NSLog(@"登陆冲突=====:%@",error);
    DDXMLNode *errorNode = (DDXMLNode *)error;
    //遍历错误节点
    for(DDXMLNode *node in [errorNode children]){
        //若错误节点有【冲突】
        if([[node name] isEqualToString:@"conflict"]){
            //有冲突 先断开连接 再提示
            [self disconnect];
            [xmppReconnect setAutoReconnect:NO];
            
            //程序运行在前台，消息正常显示  不在前台，本地通知下线信息
            if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive) {
                UILocalNotification *localNotification = [[UILocalNotification alloc] init];
                localNotification.alertAction = kXMPP_localAction;
                localNotification.alertBody = [NSString stringWithFormat:kXMPP_localNotificationMsg];//通知主体
                [localNotification setSoundName:UILocalNotificationDefaultSoundName]; //通知声音
                [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];//发送通知
            }			
			UIAlertController *alert = [UIAlertController alertControllerWithTitle:kXMPP_OfflineTitle message:kXMPP_OfflineMessage preferredStyle:UIAlertControllerStyleAlert];
			UIAlertAction *loginBtn = [UIAlertAction actionWithTitle:kXMPP_OfflineOtherBtnTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				//登录
				[self connectLogin:^(BOOL a) {
					
				}];
			}];
			
			UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:kXMPP_OfflineCancelBtnTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
				//退出登录 回调出去
				if (self.loginOutBlock) {
					self.loginOutBlock();
				}
			}];
			
			[alert addAction:cancelBtn];
			[alert addAction:loginBtn];
			UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
			UIViewController *topVC = appRootVC;
			if (nil != topVC.presentedViewController) {
				topVC = topVC.presentedViewController;
			}
			[topVC presentViewController:alert animated:YES completion:nil];
        }
    }
}

#pragma mark --------配置XML流---------
- (void)setupStream
{
    NSAssert(xmppStream == nil, @"Method setupStream invoked multiple times");
    userDefaults=[NSUserDefaults standardUserDefaults];
    
    xmppStream = [[XMPPStream alloc] init];
    
#if !TARGET_IPHONE_SIMULATOR
    {
        xmppStream.enableBackgroundingOnSocket = YES;
    }
#endif
    
    xmppReconnect = [[XMPPReconnect alloc] init];
    
    [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    [xmppStream setHostName:kXMPP_IP];
    [xmppStream setHostPort:kXMPP_PORT];
    
    
}


- (void)dealloc
{
    [self teardownStream];
}
- (void)teardownStream
{
    
    [xmppStream removeDelegate:self];
    
    [xmppReconnect deactivate];
    
    [xmppStream disconnect];
    xmppStream = nil;
    xmppReconnect = nil;
    
}
#pragma mark -app
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if ([application respondsToSelector:@selector(setKeepAliveTimeout:handler:)])
    {
        [application setKeepAliveTimeout:600 handler:^{
            
            // Do other keep alive stuff here.
        }];
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
}

@end
